#include <iostream>

using std::cout;
using std::endl;

template <typename T>
class Singleton
{
public:
    template <typename ...Args>
    static T* getInstance(Args ...args)
    {
        if(nullptr == _pInstance)
        {
            _pInstance = new T(args...);
            _ar;//实例化
        }

        return _pInstance;
    }

    static void destroy()
    {
        if(_pInstance)
        {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

private:
    class AutoRelease
    {
    public:
        AutoRelease()
        {
            cout << "AutoRelease()" << endl;
        }

        ~AutoRelease()
        {
            cout << "~AutoRelease()" << endl;
            if(_pInstance)
            {
                delete _pInstance;
                _pInstance = nullptr;
            }
        }

    };
private:
    Singleton()
    {
        cout << "Singleton()" << endl;
    }

    ~Singleton()
    {
        cout << "~Singleton()" << endl;
    }

private:
    static T *_pInstance;
    static AutoRelease _ar;
};

template <typename T>
T *Singleton<T>::_pInstance = nullptr;

template <typename T>
typename Singleton<T>::AutoRelease Singleton<T>::_ar;

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
        cout << "Point(int = 0, int = 0)" << endl;
    }

    void print() const
    {
        cout <<"(" << _ix
             << ", " << _iy
             << ")" << endl;
    }

    ~Point()
    {
        cout <<"~Point()" << endl;
    }
private:
    int _ix;
    int _iy;
};

class Point3D
{
public:
    Point3D(int ix = 0, int iy = 0, int iz = 0)
    : _ix(ix)
    , _iy(iy)
    , _iz(iz)
    {
        cout << "Point3D(int = 0, int = 0, int = 0)" << endl;
    }

    void print() const
    {
        cout <<"(" << _ix
             << ", " << _iy
             << ", " << _iz
             << ")" << endl;
    }

    ~Point3D()
    {
        cout <<"~Point3D()" << endl;
    }
private:
    int _ix;
    int _iy;
    int _iz;
};
void test()
{
    /* Point *pt1 = Singleton<Point>::getInstance(1, 2); */
    /* Point *pt2 = Singleton<Point>::getInstance(3, 4); */
    /* pt1->print(); */
    /* pt2->print(); */
}
void test2()
{
    Point3D *pt1 = Singleton<Point3D>::getInstance(1, 2, 6);
    Point3D *pt2 = Singleton<Point3D>::getInstance(3, 4, 5);
    pt1->print();
    pt2->print();
}

int main(int argc, char *argv[])
{
    test2();
    return 0;
}

